package org.example.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.service.ICodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.example.constant.RedisConstant.LOGIN_CODE;
import static org.example.constant.RedisConstant.LOGIN_CODE_TIME;

/**
 * 验证码操作
 */
@Slf4j
@Service
public class CodeServiceImpl implements ICodeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 创建验证码
     */
    @Override
    public Map<String, Object> createCode() {
        Map<String, Object> map = new HashMap<>();
        //生成验证码标识
        String uuid = IdUtil.simpleUUID();
        //生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        //变成图片二进制流
        byte[] imageBytes = lineCaptcha.getImageBytes();
        map.put("img", imageBytes);
        //验证码值
        String codeValue = lineCaptcha.getCode();
        //验证码存储在redis,有效期5分钟
        redisTemplate.opsForValue().set(LOGIN_CODE + uuid, codeValue, LOGIN_CODE_TIME, TimeUnit.MINUTES);
        map.put("codeUuid", uuid);
        return map;
    }
}
